/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef OHOS_RESIZE_DEFRAG_H
#define OHOS_RESIZE_DEFRAG_H

#include <iostream>
#include "hmfs_data.h"
#include "hmfs_utils.h"
#include "hmfs_define.h"
#include "resize_data.h"
#include "resize_utils.h"
#include "resize_operator.h"

namespace OHOS {
namespace Hmfs {

class ResizeOperator;
class ResizeDefrag{
public:
    ResizeDefrag(ResizeOperator *optPtr, std::shared_ptr<HmfsSbInfo> sbInfoPtr, std::shared_ptr<HmfsConfigData> configPtr);
    ~ResizeDefrag() = default;
    #ifdef HAVE_LINUX_BLKZONED_H
    int GetDeviceIdx(std::shared_ptr<HmfsSbInfo> sbi, uint32_t segno);
    int GetZoneIdxFromDev(std::shared_ptr<HmfsSbInfo> sbi, uint32_t segno, uint32_t devIdx);
    bool IsUsableSegment(std::shared_ptr<HmfsSbInfo> sbi, unsigned int segno);
    bool WritePointerAtZoneStart(unsigned int zoneSegno);
    #else
    bool IsUsableSegment(std::shared_ptr<HmfsSbInfo> sbi, unsigned int segno);
    bool WritePointerAtZoneStart(unsigned int zone_segno);
    #endif
    unsigned char *GetSegBitmap(struct SegEntry *se);
    unsigned char GetSegType(struct SegEntry *se);
    void SetSectionType(unsigned int segno, int type);
    int FindNextFreeBlock(uint64_t *to, int left, int wantType, bool newSec);
    uint32_t GetFreeSegments();
    unsigned short GetSegVblocks(struct SegEntry *se);
    void MoveOneCursegInfo(uint64_t from, int left, int i);
    void MoveCursegInfo(uint64_t from, int left);
    void ZeroJournalEntries();
    void WriteCursegInfo();
    void RewriteCurrentSitPage(unsigned int segno, struct sitBlockData *sitBlk);
    void FlushSitEntries();
    void UpdateSumEntry(uint32_t blkAddr, struct SummaryEntry *sum);
    int32_t HmfsMigrateBlock(uint64_t from, uint64_t to);
    int32_t HmfsDefragment(uint64_t from, uint64_t len, uint64_t to, int left);
private:
    ResizeOperator *opt_;
    std::shared_ptr<HmfsSbInfo> sbInfo_; /** sbi */
    std::shared_ptr<HmfsConfigData> config_; /** config */
};

}
}
#endif
